<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------
namespace app\Common\service;
use think\facade\Env;
class App{
    private $uniacid ;
    //产品/商品名称
    private $goods_name ;
    //授权服务器地址
    private $base_url ;
    //检查授权的地址
    private $check_url ;
    //上传小程序
    private $uploadWxapp_url ;
    private $get_auth_url ;
    //获取授权详情
    private $get_domain_param_url;
    private $http_host ;
    private $server_name ;
    private $request_time ;
    private $public_key ;
    private $domain_name_info ;
    private $is_debug  = false ;
    private $token_path;
    //@ioncube.dk myk("sha256", "cnjdbvjdnjd") -> "cff6bcac6bd92467e0cee72e5c879cdbf7044386eda8f464c817bd5c5c963d6f" RANDOM
    function __construct($uniacid=1,$is_debug = false ){
        //是否开启调试
        $this->is_debug  = $is_debug ;
        $url = dirname(__FILE__).'../../extend/token.key';
        $this->token_path = $url;
        $this->uniacid = $uniacid .'';
        $this->goods_name = config('app.AdminModelList')['app_model_name'];
		$this->base_url = base64_decode('aHR0cDovLzQ3LjExNS4yMzEuNDQ6ODMv');
        $this->check_url = $this->base_url .'auth/home.Index/index';
        $this->uploadWxapp_url = $this->base_url .'auth/home.Index/uploadWxapp';
        $this->get_auth_url = $this->base_url .'auth/home.Index/getAuth' ;
        $this->get_domain_param_url = $this->base_url .'auth/home.Index/domain_param' ;
        $this->get_wxapp_version_url = $this->base_url .'auth/home.Index/getWxappVersion' ;
        $this->clear_up_token  = $this->base_url .'auth/home.Index/clearToken' ;
        $this->http_host = $_SERVER['HTTP_HOST'];
        $this->server_name = $_SERVER['SERVER_NAME'];
        $this->request_time = $_SERVER['REQUEST_TIME'].'';
    }
    //@ioncube.dk myk("sha256", "rfurhugg") -> "12a33f0a4d7a47eb9933a78e9bcf1ad139cb7db882bb65c7b868b1e934bbb9ea" RANDOM
    public function baseUrl(){
        return $this->get_domain_param_url;
    }
    //@ioncube.dk myk("sha256", "rfurhugg") -> "12a33f0a4d7a47eb9933a78e9bcf1ad139cb7db882bb65c7b868b1e934bbb9ea" RANDOM
    public function checkUrl(){
        return $this->base_url .'auth/home.Index/index';
    }
    /**
     **@author lichuanming
     * @DataTime: 2020/6/18 19:13
     * @功能说明: 获取saas端的值
     */
    public function getsAuthConfig(){
        $this->public_key = $this->getPublicKey();
        if(empty($this->public_key )){
            return [];
        }
        $siginStr = $this->getSiginData([]);
        $result = $this->curl_post($this->get_domain_param_url ,$this->getPostData($siginStr)) ;
        $result = json_decode( $result,true);
        $param_list = $result['data']['param_list'];
        if(is_array($param_list)){
            foreach ($param_list as $key =>$item){
                $param = '';
                openssl_public_decrypt(base64_decode($item), $param, $this->public_key);
                $param_list[$key] = $param;
            }
        }
        return $param_list;
    }
    /**
     * @param $siginStr
     * @功能说明: 获取提交信息
     * @author jingshuixian
     * @DataTime: 2020-06-05 16:35
     */
    public function getPostData($siginStr)
    {
        $postData = $this->getPublicPostData();
        $postData['sigin' ] =  $siginStr;
        return $postData ;
    }
    /**
     * @author jingshuixian
     * @DataTime: 2020-06-05 16:13
     * @功能说明: 获取签名信息
     */
    public function getSiginData($extData = [] , $siginType = 1 )
    {
        $data = $this->getPublicPostData();
        if (!empty($extData)){
            $data['ext_data'] = $extData ;
        }
        ksort($data);
        $str_data = json_encode($data);
        if($siginType == 1 ){
            @openssl_public_encrypt($str_data, $encrypted, $this->public_key);
            if(empty($encrypted)){
                return  false ;
            }
            //处理特殊字符
            $encrypted = base64_encode($encrypted);
        }else{ #其他只做数据签名,不做信息加密
            $encrypted =$this->getSiginDataByHash($data);
        }
        return  $encrypted ;
    }
    /**
     * @param $data
     * @功能说明: 普通数据签名算法(只支持 str 和数组 签名 )
     * @author jingshuixian
     * @DataTime: 2020-06-06 15:10
     */
    private function getSiginDataByHash($data){
        $data['token'] = $data['token']?$data['token']:'';
        $data = is_array( $data ) ? json_encode($data)  : (is_string($data) ? $data : time() . '') . 'LongbingShuixian';
        $siginStr = hash( 'sha256', $data) ;
        return $siginStr ;
    }
    /**
     * @author jingshuixian
     * @DataTime: 2020-06-06 14:45
     * @功能说明: 获取公共提交数据
     */
    private function getPublicPostData(){
        $app_model_name =  config('app.AdminModelList')['app_model_name'];
        $token =  file_get_contents($this->token_path) ;
        $token =  $token?json_decode($token,true):'';
        if(!empty($token)){
            $token = $token['token'];
        }
        $data = [
            'uniacid' => $this->uniacid ,
            'app_model_name' => $app_model_name , //2020/6/22 新增参数 By.lichuanming
            'goods_name' => $this->goods_name,
            'http_host' => $this->http_host ,
            'server_name' => $this->server_name ,
            'request_time' => $this->request_time ,
            'token' => $token
        ];
        return $data ;
    }
    public function getCache(){
        $options = [
            'host'    => Env::get('cache.host', '127.0.0.1'),
            'port'    => Env::get('cache.port', 6379),
            'password'=> Env::get('cache.passwd', ''),
            'expire'  => Env::get('cache.expire', 0),
            'prefix'  => Env::get('cache.prefix', 'longbing_'),
        ];
        $redis = new \think\cache\driver\Redis($options);
        return $redis;
    }
    /**
     * @param $url
     * @param string $folder
     * @功能说明: 下载文件
     * @author jingshuixian
     * @DataTime: 2020-06-05 14:15
     */
    private function get_file($url, $folder = './data/upgradex/') {
        set_time_limit(24 * 60 * 60);
        $target_dir = $folder . '';
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        $newfname = date('Ymd') . rand(1000, 10000000) . uniqid() . '.zip';
        $newfname = $target_dir . $newfname;
        $file = @fopen($url, "rb");
        if ($file) {
            $newf = fopen($newfname, "wb");
            if ($newf) while (!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8) , 1024 * 8);
            }
            fclose($file);
            if ($newf) {
                fclose($newf);
            }
        }else{
            return false ;
        }
        return $newfname;
    }
    /**
     * @param $filename
     * @param $toFilepath
     * @param null $password 解压密码
     * @功能说明: 解压文件
     * @author jingshuixian
     * @DataTime: 2020-06-05 14:44
     */
    private function unzip($filename  , $toFilepath  , $password = null){
        $zip = new ZipArchive;
        $res = $zip->open($filename);
        if ($res === true){
            $password  && $zip->setPassword($password);    //解压密码
            $zip->extractTo($toFilepath);
            $zip->close();
        }
        return true ;
    }
    /**
     * @author jingshuixian
     * @DataTime: 2020-06-05 13:34
     * @功能说明: 获取秘钥
     */
    public function getPublicKey(){
        if(!empty($this->public_key)){
            return  $this->public_key ;
        }
        $siginStr = $this->getSiginData([] , 2);
        $result = $this->curl_post($this->get_auth_url  ,$this->getPostData($siginStr) ) ;
        $result = json_decode( $result,true);
        // todo 需要判断返回结果是否正确
        $this->domain_name_info = $result['data']['domain_name_info'];
        $token = $result['data']['token'];
        $resultWriteToken = $this->writein_token($token);
        $this->public_key = $result['data']['public_key'];
        return $this->public_key;
    }
    /**
     * @param $url
     * @param array $data
     * @功能说明: post 请求
     * @author jingshuixian
     * @DataTime: 2020-06-05 12:53
     */
    public function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    /**
     **@param array $token
     * @功能说明: token写入
     * @author lichuanming
     * @DataTime: 2020/6/19 11:35
     */
    private function writein_token($token):bool {
        $resultWriteToken = false;
        if(is_array($token)){
            //数据正常 直接保存
            $resultWriteToken = file_put_contents($this->token_path , json_encode($token));
        }else{
            //读取原有token 数据
            $token =  @file_get_contents($this->token_path) ;
            $token =  $token?json_decode($token,true):'';
            if(!empty($token)){
                if($token['token_expiration_time'] < time()){
                    $token['token'] = '';
                    //写入空token
                    $resultWriteToken = file_put_contents($this->token_path , json_encode($token));
                }
            }
        }
        return  $resultWriteToken?true:false;
    }
}
